package org.zetaframework.core.utils;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.ttl.TransmittableThreadLocal;
import org.slf4j.MDC;
import org.zetaframework.core.constants.Constants;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * MDC上下文工具类
 *
 * @author gcc
 */
public final class MdcContextUtil {

    private MdcContextUtil(){
    }

    private static final TransmittableThreadLocal<Map<String, String>> THREAD_LOCAL = new TransmittableThreadLocal<>() {
        @Override
        protected void beforeExecute() {
            final Map<String, String> mdc = get();
            mdc.forEach(MDC::put);
        }

        @Override
        protected void afterExecute() {
            MDC.clear();
        }

        @Override
        protected Map<String, String> initialValue() {
            return MapUtil.newHashMap();
        }
    };

    public static void putAll(Map<String, String> map) {
        map.forEach(ContextUtil::set);
    }

    public static void set(String key, Object value) {
        Map<String, String> map = getLocalMap();
        map.put(key, value == null ? StrUtil.EMPTY : value.toString());
    }

    public static <T> T get(String key, Class<T> type) {
        Map<String, String> map = getLocalMap();
        return Convert.convert(type, map.get(key));
    }

    public static <T> T get(String key, Class<T> type, Object def) {
        Map<String, String> map = getLocalMap();
        return Convert.convert(type, map.getOrDefault(key, String.valueOf(def == null ? StrUtil.EMPTY : def)));
    }

    public static String get(String key) {
        Map<String, String> map = getLocalMap();
        return map.getOrDefault(key, StrUtil.EMPTY);
    }

    /**
     * 获取ThreadLocal中的值
     * @return Map<String, String>
     */
    public static Map<String, String> getLocalMap() {
        Map<String, String> map = THREAD_LOCAL.get();
        if (map == null) {
            map = new ConcurrentHashMap<>(10);
            THREAD_LOCAL.set(map);
        }
        return map;
    }

    /**
     * 设置ThreadLocal中的值
     * @param localMap
     */
    public static void setLocalMap(Map<String, String> localMap) {
        THREAD_LOCAL.set(localMap);
    }

    /**
     * 防止内存溢出
     */
    public static void remove() {
        THREAD_LOCAL.remove();
    }

    /*********************** 链路追踪id ***********************/
    /**
     * 设置链路追踪id
     * @param traceId  String
     */
    public static void setTraceId(String traceId) { set(Constants.TRACE_ID, traceId);}

    /**
     * 获取链路追踪id
     * @return String
     */
    public static String getTraceId() { return get(Constants.TRACE_ID);}
    /*********************** 链路追踪id end ***********************/


}
